package com.wex.cookbook.utils;

import cn.hutool.core.lang.UUID;
import java.util.Base64;

import cn.hutool.json.JSONUtil;
import com.wex.cookbook.entity.Userinfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;
import java.util.Map;

/**
 * JWT工具类
 * @author : wex
 * @createTime : 2023/10/17 10:31
 */
@Component
public class JWTUtils {

    /**
     * 有效期为 30分钟
     */
    public static final Long JWT_TTL = 30 * 60 * 1000L;

    /**
     * 设置秘钥明文
     */
    public static final String JWT_KEY = "wenxinsqx999";


    public static String getUUID() {
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        return token;
    }

    /**
     * 生成token,默认30分钟过期
     * @param subject -token要存放的信息
     * @return
     */
    public static String createToken(String subject) {
        JwtBuilder builder = getJwtBuilder(subject, JWT_TTL, getUUID());
        return builder.compact();
    }

    /**
     * 生成 token
     *
     * @param subject   token中要存放的数据（json格式）
     * @param ttlMillis token超时时间
     * @return
     */
    public static String creteToken(String subject, Long ttlMillis) {
        // 设置过期时间
        JwtBuilder builder = getJwtBuilder(subject, ttlMillis, getUUID());
        return builder.compact();
    }

    /**
     * 生成token
     * @param subject
     * @param jwtTtl
     * @param uuid
     * @return
     */
    private static JwtBuilder getJwtBuilder(String subject, Long jwtTtl, String uuid) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        if (jwtTtl == null) {
            jwtTtl = JWTUtils.JWT_TTL;
        }
        long expMillis = nowMillis + jwtTtl;
        Date expDate = new Date(expMillis);
        return Jwts.builder()
                // 唯一的ID
                .setId(uuid)
                // 主题  可以是JSON数据
                .setSubject(subject)
                // 签发者
                .setIssuer("wenxin")
                // 签发时间
                .setIssuedAt(now)
                // 使用 HS256 对称加密算法签名, 第二个参数为秘钥
                .signWith(signatureAlgorithm, secretKey)
                .setExpiration(expDate);
    }

    /**
     *  生成加密后的秘钥 secretKey
     * @return
     */
    private static SecretKey generalKey() {
        byte[] encodedKey = Base64.getDecoder().decode(JWTUtils.JWT_KEY);
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }

    /**
     * 解析
     *
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseToken(String jwt) throws Exception {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }


    public static void main(String[] args) throws Exception {
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJmZjlmOGMyYjk5MmY0MWM3YmQ2ZjVjNTIxMmVjM2UyNiIsInN1YiI6IntcImlkXCI6MSxcInVzZXJuYW1lXCI6XCJ3ZXhcIixcInBhc3N3b3JkXCI6XCJCQUQxQkJCNzQ5ODEwNUEyOTY3NUE5MzRDOTRFQzQ1OFwiLFwicGFzc3dvcmRTYWx0XCI6XCI2Nzc4MFwiLFwiY3JlYXRlVGltZVwiOjE2OTc0NDY3NDIwMDAsXCJzdGF0dXNcIjoxLFwicm9sZVwiOjF9IiwiaXNzIjoid2VueGluIiwiaWF0IjoxNjk3NjgzODM0LCJleHAiOjE2OTc2ODU2MzR9.qHmekfRKLTZ0r6gKiBGq0j9CUcKzV9LAxm4mafygHCc";
        Claims claims = parseToken(token);
        String subject = claims.getSubject();
        Userinfo userinfo = JSONUtil.toBean(subject, Userinfo.class);
        System.out.println(userinfo);
    }

}
